﻿#include <iostream>
#include <thread>
#include <mutex>

// 单例类
class Singleton {
private:
    Singleton() {
        std::cout << "🔧 Singleton constructor called once by thread: "
                  << std::this_thread::get_id() << std::endl;
    }
    ~Singleton() = default;
    // 禁止拷贝和赋值
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    // 静态实例指针和一次性标志
    static Singleton* instance;
    static std::once_flag initFlag;

public:
    // 获取实例的静态方法
    static Singleton* getInstance() {
        std::call_once(initFlag, []() {
            instance = new Singleton(); // 只会执行一次
        });
        return instance;
    }

    void sayHello(int tid) {
        std::cout << "Hello from thread " << tid
                  << ", Singleton address: " << this << std::endl;
    }
};

// 静态成员定义
Singleton* Singleton::instance = nullptr;
std::once_flag Singleton::initFlag;

// 线程任务函数
void accessSingleton(int id) {
    Singleton* s = Singleton::getInstance();
    s->sayHello(id);
}

// 主函数
int main() {
    std::thread t1(accessSingleton, 1);
    std::thread t2(accessSingleton, 2);
    std::thread t3(accessSingleton, 3);
    std::thread t4(accessSingleton, 4);

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    return 0;
}
